<?php

namespace App\Http\Controllers\Admin;

use App\Exports\QhCdkeyExport;
use App\Exports\QhNetCourseCdkeyExport;
use App\Http\Requests\Admin\Qh_CdkeyBetchCreateRequest;
use App\Models\CourseColumn;
use App\Models\LearnVideo;
use App\Models\NetCourseCdkey;
use App\Models\NetCourseCdkeyGroup;
use Carbon\Carbon;
use DB;
use Illuminate\Http\JsonResponse;
use Maatwebsite\Excel\Facades\Excel;
use PHPUnit\Util\Exception;
use Throwable;

class Qh_NetCourseCdkeyController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = NetCourseCdkey::filter(\request()->all())
            ->with([
                'user' => function($q) {
                    $q->select(['id', 'username', 'nickname', 'avatar']);
                },
                'learnVideo' => function($q) {
                    $q->select(['id', 'name']);
                },
                'courseColumn' => function($q) {
                    $q->select(['id', 'name']);
                }
            ])
            ->orderByDesc('id')
            ->paginate(\request('perPage', 10));
        return $this->restful($list);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     */
    public function destroy(int $id)
    {
        $cdkey = NetCourseCdkey::findOrFail($id);
        $cdkey->delete();

        return $this->restful();
    }

    /**
     * 冻结/解冻
     * @param $id
     * @return JsonResponse|object
     * @throws Throwable
     */
    public function freeze($id) {
        $cdkey = NetCourseCdkey::findOrFail($id);

        try {
            if ($cdkey->status == 2) {
                DB::transaction(function () use ($cdkey){
                    $cdkey->status = 4;
                    $cdkey->save();

                    if ($cdkey->type == 1) {
                        unlockLearnVideo($cdkey->userId, $cdkey->activeDataId);
                    }
                    elseif ($cdkey->type == 2) {
                        $model = CourseColumn::find($cdkey->activeDataId);
                        if ($model) unlockCourseColumnResource($cdkey->userId, $model);
                    }
                });

            }
            elseif ($cdkey->status == 4) {
                DB::transaction(function () use ($cdkey){
                    $cdkey->status = 2;
                    $cdkey->save();

                    if ($cdkey->type == 1) {
                        $learnVideo = LearnVideo::find($cdkey->activeDataId);
                        if ($learnVideo) {
                            $expireAt = getLearnVideoExpireAt($learnVideo);
                            $sendRes = sendLearnVideoToUser([$cdkey->activeDataId], $cdkey->userId, $expireAt, 2);
                            if (!$sendRes) throw new Exception('解冻失败');
                        }
                    }
                    elseif ($cdkey->type == 2) {
                        $courseColumn = CourseColumn::find($cdkey->activeDataId);
                        if ($courseColumn) {
                            $resource = $courseColumn->resource;
                            if (!empty($resource)) {
                                $expireAt = getCourseColumnExpireAt($courseColumn);
                                // 题库
                                if (!empty($resource['courses'])) {
                                    $sendRes = sendCourseToUser($resource['courses'], $cdkey->userId, $expireAt, 2);
                                    if (!$sendRes) throw new Exception('解冻失败');
                                }
                                // 文档
                                if (!empty($resource['documents'])) {
                                    $sendRes = sendDocumentToUser($resource['documents'], $cdkey->userId, $expireAt, 2);
                                    if (!$sendRes) throw new Exception('解冻失败');
                                }
                                // 视频课程
                                if (!empty($resource['learn_videos'])) {
                                    $sendRes = sendLearnVideoToUser($resource['learn_videos'], $cdkey->userId, $expireAt, 5);
                                    if (!$sendRes) throw new Exception('解冻失败');
                                }

                                DB::table('user_course_column_buy_logs')->updateOrInsert([
                                    'userId' => $cdkey->userId
                                ], [
                                    'dataId' => $courseColumn->id,
                                    'getType' => 2,
                                    'expireAt' => $expireAt,
                                    'created_at' => now(),
                                    'updated_at' => now()
                                ]);
                            }
                        }
                    }
                });
            }
        }catch (\Exception $e) {
            throw new Exception('操作失败');
        }

        return $this->restful();
    }

    /**
     * 扩展生成激活码
     * @throws Throwable
     */
    public function extend()
    {
        $params = \request()->validate([
            'groupId' => 'bail|nullable|integer|exists:net_course_cdkey_groups,id',
            'expires' => 'bail|nullable|integer',
            'count' => 'bail|required|integer',
            'effective_type' => 'bail|required|int',
            'effective_days' => 'bail|nullable|int',
            'effective_hours' => 'bail|nullable|int',
            'effective_date' => 'bail|nullable|string',
        ], \request()->all());

        $cdkeyGroup = NetCourseCdkeyGroup::findOrFail($params['groupId']);

        try {
            DB::beginTransaction();
            // 生成激活码
            for ($i=0; $i<$params['count'];$i++) {
                NetCourseCdkey::create([
                    'groupId' => $params['groupId'],
                    'code' => generateCdkey(),
                    'expires' => !empty($params['expires']) ? Carbon::createFromTimestamp($params['expires'], 'Asia/Shanghai') : $cdkeyGroup->expires,
                    'dataId' => $cdkeyGroup->dataId,
                    'type' => $cdkeyGroup->type,
                    'effective_type' => !empty($params['effective_type']) ? $params['effective_type'] : null,
                    'effective_days' => !empty($params['effective_days']) ? $params['effective_days'] : null,
                    'effective_hours' => !empty($params['effective_hours']) ? $params['effective_hours'] : null,
                    'effective_date' => !empty($params['effective_date']) ? $params['effective_date'] : null,
                ]);
            }

            $cdkeyGroup->count = $cdkeyGroup->count + $params['count'];
            $cdkeyGroup->save();
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            throw new \Exception('生成失败');
        }

        return $this->restful();
    }

    /**
     * 批量删除
     * @return JsonResponse|object
     */
    public function cdkeyBatchDelete() {
        $ids = \request('ids', []);
        if (count($ids) > 0) {
            $cdkeyList = NetCourseCdkey::whereIn('id', $ids)->get();
            foreach ($cdkeyList as $cdkey) {
                $cdkey->delete();
            }
        }

        return $this->restful();
    }

    /**
     * @throws \Exception
     */
    public function export()
    {
        $ids = request('ids', []);
        if (count($ids) < 1)  throw new \Exception('缺少参数');
        $filename = '网课激活码'.time().'.xlsx';

        try {
            $result = Excel::store(new QhNetCourseCdkeyExport(['ids' => $ids]), $filename, 'public');
            if (!$result) throw new \Exception('导出失败');
        }catch (\Exception $e) {
            throw new \Exception('导出失败');
        }

        return $this->restful([
            'filename' => $filename,
            'url' => \Storage::disk('public')->url($filename)
        ]);
    }

    /**
     * 批量创建
     * @param Qh_CdkeyBetchCreateRequest $request
     * @return JsonResponse|object
     */
    public function cdkeyBatchCreate(Qh_CdkeyBetchCreateRequest $request) {
        $params = $request->validated();

        $cdkey = [];
        // 双表
        // $cdkeyGroup

        for ($i=0; $i<$params['count'];$i++) {
            $cdkey[] = [
                'code' => 'CDKEY'.rand(1000000, 9999999),
            ];
            // NetCourseCdkey::create([
            //     'code' => 'CDKEY'.rand(1000000, 9999999),
            //     'courseId' => $params['courseId']
            // ]);
        }

        // 入库
        $cdkeyGroup = NetCourseCdkeyGroup::create($params);

        return $this->restful();
    }
}
